package com.ihr360.expr.function.excel;

import com.ihr360.expr.ExprBoolean;
import com.ihr360.expr.ExprDouble;
import com.ihr360.expr.ExprError;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.ExprMissing;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.AbstractFunction;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprNumber;
import com.ihr360.expr.utils.ExprUtils;

public class IF extends AbstractFunction{
    @Override
    public Expr evaluate(IEvaluationContext context, Expr[] args) throws ExprException {
        if (args.length<2){
            throw new ExprException("Too few arguments entered for function IF");
        }else if (args.length>3){
            throw new ExprException(
                    "Too many arguments entered for function IF");
        }
        Expr condition = ExprUtils.evalArg(context, args[0]);
        Expr yesResult = args[1];
        Expr noResult = null;
        if (args.length==2){
            noResult= ExprBoolean.FALSE;
        }else{
            noResult= args[2];
        }
        if (condition instanceof ExprNumber) {
            Expr res = ExprUtils.evalArg(context,
                    ((ExprNumber) condition).booleanValue() ? yesResult : noResult);
            if (res instanceof ExprMissing) {
                res = ExprDouble.ZERO;
            }
            return res;
        }
        return ExprError.VALUE;
    }
}